package com.knowledge.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import com.knowledge.DAO.*;
import com.opensymphony.xwork2.ActionSupport;

public class AddLabelAction  extends ActionSupport{
	
	private String userId;
	private String knowledgeId;
	private List<String> labelList = new ArrayList<String>();
	private Connection con=null;
	private Statement smt=null;
	private ResultSet rs=null;
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		
		int flag=0;
		con = DBpool.getConnection();
		
		for(String label:this.getLabelList())
		{
			String sql="select * from label where name='"+label+"'";
			smt=con.createStatement();
			rs=smt.executeQuery(sql);
			
			if(rs.next())
			{
			
				 String labelId=rs.getString("Id");
				 int ownNum=rs.getInt("ownNum")+1;
				 sql = "select id from label_knowledge where labelId=" + labelId + " and knowledgeId=" + knowledgeId;
				 ResultSet result = smt.executeQuery(sql);
				 if(result.next()){
					 result.close();
					 rs.close();
					 continue;
				 }else
					 result.close();
				
				 sql="update label set ownNum="+ownNum
				     +" where name='"+label+"'";
				
				 smt.executeUpdate(sql);
				 
				 sql="insert into label_knowledge (labelId,knowledgeId) values('"+labelId+"','"+knowledgeId+"') ";
				 smt.executeUpdate(sql);
			}
			else
			{
				String userId=this.getUserId();
				sql="insert into label (name,userId,ownNum) values('"+label+"','"+userId+"',1)";
				smt.executeUpdate(sql);
				
				String labelId=null;
				sql="select * from label where name='"+label+"'";
				ResultSet result = smt.executeQuery(sql);
				
				if(result.next())
				{
					labelId=result.getString("Id");
				}
				result.close();
				sql="insert into label_knowledge (labelId,knowledgeId) values('"+labelId+"','"+knowledgeId+"') ";
				smt.executeUpdate(sql);
			}

		}
		{
			rs.close();
			smt.close();
			con.close();
		}
		
		return SUCCESS;
	}

	public List<String> getLabelList() {
		return labelList;
	}
	public void setLabelList(List<String> labelList) {
		this.labelList = labelList;
	}


	public String getUserId() {
		return userId;
		
	}


	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	public void setModel(Object id){
		this.knowledgeId = id.toString();
		}



}
